﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SimpleServiceBus.Utilities.Network
{
    public static class UriHelper
    {
        public static IPAddress ToIPAddress(this Uri uri)
        {
            return ToIPAddress(uri, AddressFamily.InterNetwork);
        }

        public static IPAddress ToIPAddress(this Uri uri,AddressFamily preferredAddressFamily)
        {
            if (uri == null)
                return IPAddress.Any;

            string host = uri.Host.ToLower();

            if (host == "any" || host == "this")
                return IPAddress.Any;

            if (host == "localhost")
                return IPAddress.Loopback;

            if (host == "none")
                return IPAddress.None;

            IPHostEntry entry = Dns.GetHostEntry(host);
            
            foreach (IPAddress address in entry.AddressList)
            {
                if (address.AddressFamily == preferredAddressFamily)
                    return address;
            }

            //Preferred family cannot be found, we'll return the first in the list
            if (entry.AddressList.Length > 0)
                return entry.AddressList[0];

            throw new Exception("An IPAddress could not be found for " + uri);
        }
    }
}
